import time

from PyQt5.QtCore import QThread, pyqtSignal

import errorhandle


import socket
import traceback
import numpy as np


class UDPServer(QThread):
    trigger = pyqtSignal(np.ndarray)
    triggerF = pyqtSignal(np.ndarray)
    triggerExcept = pyqtSignal(int)

    def __init__(self, server_config):
        super().__init__()
        self.server_config = server_config
        self.is_running = False

    def generate_server(self):
        try:
            self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            address = (self.server_config["IP"], self.server_config["PORT"])
            self.server_socket.bind(address)
            # self.server_socket.settimeout(self.server_config["TIMEOUT"])
            self.is_running = True
            return 0
        except Exception as e:
            traceback.print_exc()
            return errorhandle.START_SERVER_EXCEPTION, e, self.server_config

    def run(self):
        while self.is_running:
            receive_data, client = self.server_socket.recvfrom(10000)
            s11 = np.frombuffer(receive_data, dtype=np.float64)
            if len(s11) == 2:
                self.triggerF.emit(s11)
                self.server_socket.sendto(b'OK', client)
            elif len(s11) == 1:
                self.triggerExcept.emit(int(s11[0]))
            else:
                self.trigger.emit(s11)
            time.sleep(self.server_config['FREQ'])

    def stop(self):
        self.is_running = False
        self.server_socket.close()
